package com.newsee.remote.storehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.SystemConfig;
import com.newsee.remote.common.bean.JsonResult;
import com.newsee.remote.common.bean.JsonReturn;
import com.newsee.remote.common.database.entity.ShStorehouse;
import com.newsee.remote.common.database.mapper.ShStorehouseMapper;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.common.utils.tools.SapXmlBuildUntil;
import com.newsee.remote.common.utils.webservice.HttpWebserviceExecutor;
import com.newsee.remote.storehouse.service.IShStorehouseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 仓库服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-11-06
 */
@Slf4j
@Service
public class ShStorehouseServiceImpl extends ServiceImpl<ShStorehouseMapper, ShStorehouse> implements IShStorehouseService {

    @Autowired
    private SystemConfig systemConfig;

    @Value("${houseUrl}")
    private String houseUrl;

    /**
     * sap请求仓库方法url
     */
    private final static String HOUSE_METHOD = "MT_IF1041_WAREHOUSE_INFO_REQ";

    /**
     * 仓库请求start string
     */
    private final static String XML_START = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sunac:erp:warehouse_info\">\n";

    @Override
    public JsonResult pushStoreHouse(String startTime, String endTime) {
        //查询某时间段内的的增量数据（默认前一天的增量数据）
        List<ShStorehouse> storehouses = getNeedUpdateStores(startTime, endTime);
        if (CollectionUtils.isEmpty(storehouses)) {
            return JsonReturn.succ("当前时间段或前一天没有增量仓库数据数据");
        }

        //请求业务体
        String message = getMessage(storehouses);
        //组装xml请求sap
        String request = SapXmlBuildUntil.makeXml(XML_START, HOUSE_METHOD, systemConfig.getSapReqTarSys(), message);
        String response = HttpWebserviceExecutor.doHttpMethodSap(houseUrl, request, systemConfig.getSapAccount(), systemConfig.getSapPassword());
        return JsonReturn.succ(response);
    }

    /**
     * 获取请求的业务体字符串
     *
     * @param storehouses 所有的仓库数据
     * @return 业务题字符串
     */
    private String getMessage(List<ShStorehouse> storehouses) {
        StringBuilder message = new StringBuilder();
        message.append("<MESSAGE>\n");
        for (ShStorehouse storehouse : storehouses) {
            message.append("<REQ_ITEM>\n");

            message.append("<StoreHouseCode>");
            if (StringUtils.isNotBlank(storehouse.getStoreHouseCode())) {
                message.append(storehouse.getStoreHouseCode());
            }
            message.append("</StoreHouseCode>\n");

            message.append("<StoreHouseName>");
            if (StringUtils.isNotBlank(storehouse.getStoreHouseName())) {
                message.append(storehouse.getStoreHouseName());
            }
            message.append("</StoreHouseName>\n");

            message.append("<CostCode>");
            if (StringUtils.isNotBlank(storehouse.getCostCode())) {
                message.append(storehouse.getCostCode());
            }
            message.append("</CostCode>\n");

            message.append("<CostName>");
            if (StringUtils.isNotBlank(storehouse.getCostName())) {
                message.append(storehouse.getCostName());
            }
            message.append("</CostName>\n");

            message.append("</REQ_ITEM>\n");
        }
        message.append("</MESSAGE>\n");
        return message.toString();
    }

    /**
     * 获取增量修改的仓库数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 仓库数据s
     */
    private List<ShStorehouse> getNeedUpdateStores(String startTime, String endTime) {
        //没传时间默认取前一天增量的数据
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)) {
            Date date = new Date();
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, -1);
            Date yesterday = c.getTime();
            startTime = DateUtils.format(yesterday, "yyyy-MM-dd HH:mm:ss.sss");
            c.setTime(date);
            endTime = DateUtils.format(date, "yyyy-MM-dd HH:mm:ss.sss");
        }

        QueryWrapper<ShStorehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("CreateDate", startTime, endTime)
                .or()
                .between("UpdateDate", startTime, endTime);
        return list(queryWrapper);
    }
}
